/**
 * Project Name:smcs-mass-dns-ipcheck
 * File Name:IpAllocateConflictChecker.java
 * Package Name:com.surfilter.massdata.ipcheck.mr.helper
 * Date:2015-3-28下午02:17:30
 * Copyright (c) 2015, Shenzhen Surfilter Network Technology Co.,Ltd All Rights Reserved.
 * 
*/

package com.surfilter.massdata.spark.util.ipcheck;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.surfilter.massdata.spark.bean.ipcheck.ErrIp;
import com.surfilter.massdata.spark.bean.ipcheck.IpBean;
import com.surfilter.massdata.spark.bean.ipcheck.ObjectInfo;

import scala.Tuple2;

/**
 * ClassName:IpAllocateConflictChecker <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason:   TODO ADD REASON. <br/>
 * Date:     2015-3-28 下午02:17:30 <br/>
 * @author   sunkai
 * @version  
 * @since    JDK 1.7
 * @see      
 */
public class IpAllocateConflictChecker {
	
	public static ObjectInfo allocateConflictCheck(List<IpBean> reduceAllocateList,Map<String,String> optorIds) throws IOException, InterruptedException{
		ObjectInfo objectInfo=new ObjectInfo();
		Integer hold_self = 0;
		Integer other_three = 0;
		Integer re_allot = 0;
		Integer listSize = reduceAllocateList.size();
		
		List<IpBean> hold_self_list = Lists.newArrayList();//自带IP集合
		List<IpBean> other_three_list = Lists.newArrayList();//其他另外三种分配 分配且使用、自用、预留
		List<IpBean> re_allot_list = Lists.newArrayList();//再分配的集合
		
		String storageType = "";
		String tfFlag = "";
		boolean isOpt = true;//设置IP分配信息列表里面是否有运营商自带IDC 自带标识
		for(IpBean ip : reduceAllocateList){
			storageType = ip.getStorageType();
			tfFlag = ip.getTflag();
			Long fpfs = ip.getFpfs();
			if(fpfs.equals(IpAllocateType.HOLDING_BY_SELF.getTypeValue())){//如果分配方式为自带
				hold_self += 1;
				if(!optorIds.containsKey(String.valueOf(ip.getBbdw_id()))){//判断是IDC还是运营商报的自带
					isOpt = false;
				}
				hold_self_list.add(ip);
				
			}else if(fpfs.equals(IpAllocateType.ALLOCATE_AND_USE.getTypeValue()) || 
					fpfs.equals(IpAllocateType.RESERVE.getTypeValue()) || //如果是预留自用分配且使用
					fpfs.equals(IpAllocateType.USE_BY_SELF.getTypeValue())){
					other_three += 1;
					other_three_list.add(ip);
			}else if(fpfs.equals(IpAllocateType.RE_ALLOCATE.getTypeValue())){//再分配
					re_allot += 1;
					re_allot_list.add(ip);
			}
		}
		
		if(listSize > 1 && !isOpt){
//			redisDao.hset(IpCheckConstants.CONFLICT_DATA_KEY, key.toString(), "");
			Map<Long, List<Tuple2<Long,String>>> bbdwAndIdMap = Maps.newTreeMap();
			for(IpBean ipBean : hold_self_list){
				List<Tuple2<Long,String>> idsList = bbdwAndIdMap.get(ipBean.getBbdw_id());
				if(idsList == null){
					idsList = Lists.newArrayList();
				}
				idsList.add(new Tuple2<Long,String>(ipBean.getId(),ipBean.getConflictMsg()));
				bbdwAndIdMap.put(ipBean.getBbdw_id(), idsList);
			}
			String bbdws = "";
			String regionIds = "";
			String jsonStr="";
			for(Entry<Long, List<Tuple2<Long,String>>> entry : bbdwAndIdMap.entrySet()){
				Long bbdwId = entry.getKey();
				List<Tuple2<Long,String>> ids = entry.getValue();
				Long[] idsArr = new Long[ids.size()];
				Map<Long,String> map=new HashMap<Long,String>();
						
				for(int i=0;i<ids.size();i++){
					idsArr[i]=ids.get(i)._1;
					map.put(ids.get(i)._1, ids.get(i)._2);
				}
				Arrays.sort(idsArr);
				for(Long id : idsArr){
					bbdws += bbdwId + ",";
					regionIds += storageType + "_" + tfFlag + "_" + id + ",";
					jsonStr+=map.get(id)+"\001";
				}
			}
			bbdws = bbdws.substring(0, bbdws.length() - 1);
			regionIds = regionIds.substring(0, regionIds.length() - 1);
			jsonStr = jsonStr.substring(0, jsonStr.length() - 1);
			ErrIp errIp = new ErrIp();
			errIp.setBbdws(bbdws);
			errIp.setRegionIds(regionIds);
			errIp.setJsonStr(jsonStr);
			if(storageType.equals(IpCheckConstants.BEIAN)){
				errIp.setConflictType(ConflictType.IP_ALLOCATE_CONFLICT_ERROR.getTypeValue());
				errIp.setStorageType(IpCheckConstants.BEIAN);
			}else{
				errIp.setConflictType(ConflictType.IP_ALLOCATE_CONFLICT_ERROR2.getTypeValue());
				errIp.setStorageType(IpCheckConstants.UPLOAD);
			}
			objectInfo.setResult(false);
			objectInfo.setErrInfo(errIp);
			return objectInfo;
			//如果IP出现多次分配，其中出现自带分配信息
		}else if(other_three>1 && hold_self == 1&&isOpt){
			String bbdws = "";
			String regionIds = "";
			String jsonStr = "";
			if(other_three > 0){
//				redisDao.hset(IpCheckConstants.CONFLICT_DATA_KEY, key.toString(), "");''
//				log.info("chcker131冲突IP:" + newIp);
				Map<Long, List<Tuple2<Long,String>>> bbdwAndIdMap = Maps.newTreeMap();
				for(IpBean ipBean : hold_self_list){
					List<Tuple2<Long,String>> idsList  = bbdwAndIdMap.get(ipBean.getBbdw_id());
					if(idsList == null){
						idsList = Lists.newArrayList();
					}
					idsList.add(new Tuple2<Long,String>(ipBean.getId(),ipBean.getConflictMsg()));
					bbdwAndIdMap.put(ipBean.getBbdw_id(), idsList);
				}
				for(IpBean ipBean : other_three_list){
					List<Tuple2<Long,String>> idsList = bbdwAndIdMap.get(ipBean.getBbdw_id());
					if(idsList == null){
						idsList = Lists.newArrayList();
					}
					idsList.add(new Tuple2<Long,String>(ipBean.getId(),ipBean.getConflictMsg()));
					bbdwAndIdMap.put(ipBean.getBbdw_id(), idsList);
				}
				
				for(Entry<Long,List<Tuple2<Long,String>>> entry : bbdwAndIdMap.entrySet()){
					Long bbdwId = entry.getKey();
					List<Tuple2<Long,String>> ids = entry.getValue();
					Long[] idsArr = new Long[ids.size()];
					Map<Long,String> map=new HashMap<Long,String>();
					for(int i=0;i<ids.size();i++){
						idsArr[i]=ids.get(i)._1;
						map.put(ids.get(i)._1, ids.get(i)._2);
					}
					Arrays.sort(idsArr);
					for(Long id : idsArr){
						bbdws += bbdwId + ",";
						regionIds += storageType + "_" + tfFlag + "_" + id + ",";
						jsonStr+=map.get(id)+"\001";
					}
				}
			}else if(other_three == 0){   //不需要
//			    redisDao.hset(IpCheckConstants.CONFLICT_DATA_KEY, key.toString(), "");
				Map<Long, List<Tuple2<Long,String>>> bbdwAndIdMap = Maps.newTreeMap();
				for(IpBean ipBean : reduceAllocateList){
					List<Tuple2<Long,String>> idsList = bbdwAndIdMap.get(ipBean.getBbdw_id());
					if(idsList == null){
						idsList = Lists.newArrayList();
					}
					idsList.add(new Tuple2<Long,String>(ipBean.getId(),ipBean.getConflictMsg()));
					bbdwAndIdMap.put(ipBean.getBbdw_id(), idsList);
				}
				for(Entry<Long, List<Tuple2<Long,String>>> entry : bbdwAndIdMap.entrySet()){
					Long bbdwId = entry.getKey();
					List<Tuple2<Long,String>> ids = entry.getValue();
					Long[] idsArr = new Long[ids.size()];
					Map<Long,String> map=new HashMap<Long,String>();
					for(int i=0;i<ids.size();i++){
						idsArr[i]=ids.get(i)._1;
						map.put(ids.get(i)._1, ids.get(i)._2);
					}
					Arrays.sort(idsArr);
					for(Long id : idsArr){
						bbdws += bbdwId + ",";
						regionIds += storageType + "_" + tfFlag + "_" + id + ",";
						jsonStr+=map.get(id)+"\001";
					}
				}
			}
			if(bbdws.length() > 1 && regionIds.length() > 1){
				bbdws = bbdws.substring(0, bbdws.length() - 1);
				regionIds = regionIds.substring(0, regionIds.length() - 1);
				jsonStr = jsonStr.substring(0, jsonStr.length() - 1);
				ErrIp errIp = new ErrIp();
				errIp.setBbdws(bbdws);
				errIp.setRegionIds(regionIds);
				errIp.setJsonStr(jsonStr);
				if(storageType.equals(IpCheckConstants.BEIAN)){
					errIp.setConflictType(ConflictType.IP_ALLOCATE_CONFLICT_ERROR.getTypeValue());
					errIp.setStorageType(IpCheckConstants.BEIAN);
				}else{
					errIp.setConflictType(ConflictType.IP_ALLOCATE_CONFLICT_ERROR2.getTypeValue());
					errIp.setStorageType(IpCheckConstants.UPLOAD);
				}
				objectInfo.setResult(false);
				objectInfo.setErrInfo(errIp);
				return objectInfo;
			}
		}else if(listSize > 1 && hold_self == 0){
			if(other_three == 1){
				for(IpBean ipBean : reduceAllocateList){
					if((ipBean.getIsPass() == null || ipBean.getIsPass() == true) && ipBean.getBbdw_id().equals(other_three_list.get(0).getBbdw_id()) && !ipBean.getId().equals(other_three_list.get(0).getId())){
//						redisDao.hset(IpCheckConstants.CONFLICT_DATA_KEY, key.toString(), "");
						other_three_list.get(0).setIsPass(false);
//						ipBean.setIsPass(false);
						ErrIp errIp = new ErrIp();
						errIp.setBbdws(ipBean.getBbdw_id().toString());
						errIp.setRegionIds(ipBean.getStorageType() + "_" + ipBean.getTflag() + "_" + ipBean.getId() + "," + other_three_list.get(0).getStorageType() + "_" + other_three_list.get(0).getTflag() + "_" + other_three_list.get(0).getId());
						errIp.setJsonStr(ipBean.getConflictMsg()+"\001"+other_three_list.get(0).getConflictMsg());
						if(ipBean.getStorageType().equals(IpCheckConstants.BEIAN)){
								 errIp.setConflictType(ConflictType.IP_ALLOCATE_CONFLICT_ERROR.getTypeValue());
								 errIp.setStorageType(IpCheckConstants.BEIAN);
							}else if(ipBean.getStorageType().equals(IpCheckConstants.UPLOAD)){
								errIp.setConflictType(ConflictType.IP_ALLOCATE_CONFLICT_ERROR2.getTypeValue());
								errIp.setStorageType(IpCheckConstants.UPLOAD);
							}
						objectInfo.setResult(false);
						objectInfo.setErrInfo(errIp);
						return objectInfo;
					}
				}
					return reAllocateCheck(reduceAllocateList);
			} else if(other_three == 0){
					return reAllocateCheck(reduceAllocateList);
			} else if(other_three >= 2){
//				redisDao.hset(IpCheckConstants.CONFLICT_DATA_KEY, key.toString(), "");
				String bbdws = "";
				String regionIds = "";
				String jsonStr="";
				Map<Long, List<Tuple2<Long,String>>> bbdwAndIdMap = Maps.newTreeMap();
				for(IpBean ipBean : other_three_list){
					List<Tuple2<Long,String>> idsList = bbdwAndIdMap.get(ipBean.getBbdw_id());
					if(idsList == null){
						idsList = Lists.newArrayList();
					}
					idsList.add(new Tuple2<Long,String>(ipBean.getId(),ipBean.getConflictMsg()));
					bbdwAndIdMap.put(ipBean.getBbdw_id(), idsList);
				}
				for(Entry<Long, List<Tuple2<Long,String>>> entry : bbdwAndIdMap.entrySet()){
					Long bbdwId = entry.getKey();
					List<Tuple2<Long,String>> ids = entry.getValue();
					
					Long[] idsArr = new Long[ids.size()];
					Map<Long,String> map=new HashMap<Long,String>();
					for(int i=0;i<ids.size();i++){
						idsArr[i]=ids.get(i)._1;
						map.put(ids.get(i)._1, ids.get(i)._2);
					}
					Arrays.sort(idsArr);
					for(Long id : idsArr){
						bbdws += bbdwId + ",";
						regionIds += storageType + "_" + tfFlag + "_" + id + ",";
						jsonStr+=map.get(id)+"\001";
					}
				}
				ErrIp errIp = new ErrIp();
				errIp.setBbdws(bbdws.substring(0, bbdws.length() - 1));
				errIp.setRegionIds(regionIds.substring(0, regionIds.length() - 1));
				errIp.setJsonStr(jsonStr);
				if(storageType.equals(IpCheckConstants.BEIAN)){
					errIp.setConflictType(ConflictType.IP_ALLOCATE_CONFLICT_ERROR.getTypeValue());
					errIp.setStorageType(IpCheckConstants.BEIAN);
				}else{
					errIp.setConflictType(ConflictType.IP_ALLOCATE_CONFLICT_ERROR2.getTypeValue());
					errIp.setStorageType(IpCheckConstants.UPLOAD);
				}
				objectInfo.setResult(false);
				objectInfo.setErrInfo(errIp);
				return objectInfo;
				
			}
		}
		objectInfo.setResult(true);
		return objectInfo;
	}
	
	public static ObjectInfo reAllocateCheck(List<IpBean>reduceAllocateList) throws IOException, InterruptedException{
		ObjectInfo objectInfo=new ObjectInfo();
		for(int i = 0 ; i < reduceAllocateList.size() ; i++){
			if(reduceAllocateList.get(i).getFpfs().equals(IpAllocateType.RE_ALLOCATE.getTypeValue())){
				IpBean ipOne = reduceAllocateList.get(i);
				if(!new Boolean(false).equals(ipOne.getIsPass())){
					for(int j = i + 1 ; j < reduceAllocateList.size() ; j++){
						if(reduceAllocateList.get(j).getFpfs().equals(IpAllocateType.RE_ALLOCATE.getTypeValue())){
							IpBean ipTwo = reduceAllocateList.get(j);
							if(ipOne.getBbdw_id().equals(ipTwo.getBbdw_id())){
								if(ipOne.getFpdx().equals(ipTwo.getFpdx())){
									//a分配给b a分配给b
//									ipOne.setIsPass(false);
//									ipTwo.setIsPass(false);
									
									/*redisDao.hset(IpCheckConstants.CONFLICT_DATA_KEY, key.toString(), "");
//									log.info("chcker287冲突IP:" + newIp);
									ErrorIpSeg ipSeg = new ErrorIpSeg();
									ipSeg.setBbdws(String.valueOf(ipOne.getBbdw_id()));
									if(ipOne.getId() > ipTwo.getId()){
										ipSeg.setRegionIds(ipOne.getStorageType() + "_" + ipOne.getTflag() + "_" + ipOne.getId() + "," + ipTwo.getStorageType() + "_" + ipTwo.getTflag() + "_" + ipTwo.getId());
									}else{
										ipSeg.setRegionIds(ipTwo.getStorageType() + "_" + ipTwo.getTflag() + "_" + ipTwo.getId() + "," + ipOne.getStorageType() + "_" + ipOne.getTflag() + "_" + ipOne.getId());
									}
									if(ipOne.getStorageType().equals(IpCheckConstants.BEIAN)){
										ipSeg.setConflictType(ConflictType.IP_ALLOCATE_REPEAT_ERROR.getTypeValue());
										ipSeg.setStorageType(IpCheckConstants.BEIAN);
									}else if(ipOne.getStorageType().equals(IpCheckConstants.UPLOAD)){
										ipSeg.setConflictType(ConflictType.IP_ALLOCATE_REPEAT_ERROR2.getTypeValue());
										ipSeg.setStorageType(IpCheckConstants.UPLOAD);
									}
									ResponseObj obj = CommonUtil.mergeConflictIpSeg(ipSeg, newIp, conflictQsip, conflictZzip, errorIpSeg, mos, log);
									return obj;*/	//a分配给b a分配给b
//									ipOne.setIsPass(false);
//									ipTwo.setIsPass(false);
									
									/*redisDao.hset(IpCheckConstants.CONFLICT_DATA_KEY, key.toString(), "");
//									log.info("chcker287冲突IP:" + newIp);
									ErrorIpSeg ipSeg = new ErrorIpSeg();
									ipSeg.setBbdws(String.valueOf(ipOne.getBbdw_id()));
									if(ipOne.getId() > ipTwo.getId()){
										ipSeg.setRegionIds(ipOne.getStorageType() + "_" + ipOne.getTflag() + "_" + ipOne.getId() + "," + ipTwo.getStorageType() + "_" + ipTwo.getTflag() + "_" + ipTwo.getId());
									}else{
										ipSeg.setRegionIds(ipTwo.getStorageType() + "_" + ipTwo.getTflag() + "_" + ipTwo.getId() + "," + ipOne.getStorageType() + "_" + ipOne.getTflag() + "_" + ipOne.getId());
									}
									if(ipOne.getStorageType().equals(IpCheckConstants.BEIAN)){
										ipSeg.setConflictType(ConflictType.IP_ALLOCATE_REPEAT_ERROR.getTypeValue());
										ipSeg.setStorageType(IpCheckConstants.BEIAN);
									}else if(ipOne.getStorageType().equals(IpCheckConstants.UPLOAD)){
										ipSeg.setConflictType(ConflictType.IP_ALLOCATE_REPEAT_ERROR2.getTypeValue());
										ipSeg.setStorageType(IpCheckConstants.UPLOAD);
									}
									ResponseObj obj = CommonUtil.mergeConflictIpSeg(ipSeg, newIp, conflictQsip, conflictZzip, errorIpSeg, mos, log);
									return obj;*/
									
									ipTwo.setIsPass(true);
									
								}else if(!ipOne.getFpdx().equals(ipTwo.getFpdx())){
									//a分配给b a分配给c  
//									ipOne.setIsPass(false);
//									ipTwo.setIsPass(false);
//									redisDao.hset(IpCheckConstants.CONFLICT_DATA_KEY, key.toString(), "");
//									log.info("chcker309冲突IP:" + newIp);
									ErrIp errIp = new ErrIp();
									errIp.setBbdws(String.valueOf(ipOne.getBbdw_id()));
									if(ipOne.getId() > ipTwo.getId()){
										errIp.setRegionIds(ipOne.getStorageType() + "_" + ipOne.getTflag() + "_" + ipOne.getId() + "," + ipTwo.getStorageType() + "_" + ipTwo.getTflag() + "_" + ipTwo.getId());
										errIp.setJsonStr(ipOne.getConflictMsg()+"\001"+ipTwo.getConflictMsg());
									}else{
										errIp.setRegionIds(ipTwo.getStorageType() + "_" + ipTwo.getTflag() + "_" + ipTwo.getId() + "," + ipOne.getStorageType() + "_" + ipOne.getTflag() + "_" + ipOne.getId());
										errIp.setJsonStr(ipTwo.getConflictMsg()+"\001"+ipOne.getConflictMsg());
									}
									if(ipOne.getStorageType().equals(IpCheckConstants.BEIAN)){
										errIp.setConflictType(ConflictType.IP_ALLOCATE_CONFLICT_ERROR.getTypeValue());
										errIp.setStorageType(IpCheckConstants.BEIAN);
									}else if(ipOne.getStorageType().equals(IpCheckConstants.UPLOAD)){
										errIp.setConflictType(ConflictType.IP_ALLOCATE_CONFLICT_ERROR2.getTypeValue());
										errIp.setStorageType(IpCheckConstants.UPLOAD);
									}
									objectInfo.setResult(false);
									objectInfo.setErrInfo(errIp);
									return objectInfo;
								}else{
									ipTwo.setIsPass(true);
								}
							}else if(!ipOne.getBbdw_id().equals(ipTwo.getBbdw_id())){
								//a分配给b c分配给b
								if(ipOne.getFpdx().equals(ipTwo.getFpdx())){
//									ipOne.setIsPass(false);
//									ipTwo.setIsPass(false);
//									redisDao.hset(IpCheckConstants.CONFLICT_DATA_KEY, key.toString(), "");
//									log.info("chcker335冲突IP:" + newIp);
									ErrIp errIp = new ErrIp();
									if(ipOne.getBbdw_id() > ipTwo.getBbdw_id()){
										errIp.setBbdws(ipOne.getBbdw_id() + "," + ipTwo.getBbdw_id());
										errIp.setRegionIds(ipOne.getStorageType() + "_" + ipOne.getTflag() + "_" + ipOne.getId() + "," + ipTwo.getStorageType() + "_" + ipTwo.getTflag() + "_" + ipTwo.getId());
										errIp.setJsonStr(ipOne.getConflictMsg()+"\001"+ipTwo.getConflictMsg());
									}else{
										errIp.setBbdws(ipTwo.getBbdw_id() + "," + ipOne.getBbdw_id());
										errIp.setRegionIds(ipTwo.getStorageType() + "_" + ipTwo.getTflag() + "_" + ipTwo.getId() + "," + ipOne.getStorageType() + "_" + ipOne.getTflag() + "_" + ipOne.getId());
										errIp.setJsonStr(ipTwo.getConflictMsg()+"\001"+ipOne.getConflictMsg());
									}
									if(ipOne.getStorageType().equals(IpCheckConstants.BEIAN)){
										errIp.setConflictType(ConflictType.IP_ALLOCATE_CONFLICT_ERROR.getTypeValue());
										errIp.setStorageType(IpCheckConstants.BEIAN);
									}else if(ipOne.getStorageType().equals(IpCheckConstants.UPLOAD)){
										errIp.setConflictType(ConflictType.IP_ALLOCATE_CONFLICT_ERROR2.getTypeValue());
										errIp.setStorageType(IpCheckConstants.UPLOAD);
									}
									
									objectInfo.setResult(false);
									objectInfo.setErrInfo(errIp);
									return objectInfo;
								}else{
									ipTwo.setIsPass(true);
								}
							}
						}else{
							continue;
						}
					}
				}else{
					continue;
				}
			}else{
				continue;
			}// end if-else
		}//end for
		objectInfo.setResult(true);
		return objectInfo;
	}
	

}
